import axios from 'axios';
import { get_token } from './auth';
import { message } from 'antd';
const config=window.APP_Config;
// 创建一个 axios 实例
const service = axios.create({
    baseURL: config.apiBaseUrl,
    timeout: 20000,
    headers: {
        'Content-Type': 'application/json'
    }
});

// 错误提示控制标记
let isErrorShown = {
    401: false,
    403: false,
    network: false
};

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        config.headers['Authorization'] = `Bearer ${get_token()}`;
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.code !== 0 && res.code !== -1) {
            return Promise.reject(new Error(res.message || 'Error'));
        } else {
            return res;
        }
    },
    error => {
        const status = error.response?.status;
        
        // 重置所有标记（可以根据需要调整重置时机）
        const resetFlags = () => {
            setTimeout(() => {
                isErrorShown = {
                    401: false,
                    403: false,
                    network: false
                };
            }, 1000);
        };
        
        if (status === 401 && !isErrorShown[401]) {
            isErrorShown[401] = true;
            message.error("登录已过期，请重新登录！");
            setTimeout(() => {
                window.location.href = '/login';
                resetFlags();
            }, 1000);
        }

        if (status === 403 && !isErrorShown[403]) {
            isErrorShown[403] = true;
            message.error("您没有访问权限");
            window.location.href = '/403';
            resetFlags();
        }
        
        if (!status && !isErrorShown.network) {
            isErrorShown.network = true;
            message.error("网络错误，请稍后重试");
             setTimeout(() => {
              //  window.location.href = '/login';
                resetFlags();
            }, 1000);
         
        }
        
        return Promise.reject(error);
    }
);

export default service;
